package com.yatop.lalmbda.ai;


import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.yatop.lalmbda.ai.temu.mock.MockProduct;
import com.yuyaogc.lowcode.engine.util.JsonUtil;
import com.yuyaogc.lowcode.engine.util.OkHttpClient;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.http.HttpHeaders;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * Temu
 */
public class TemuMockApi {
    public static final String BASE_URL = "https://seller.kuajingmaihuo.com/bg/quiet/api/mms";
    public final static String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36";
    public static final String COOKIE = "api_uid=CmiQKGfJqT12AABUXciqAg==; _nano_fp=XpmYXpPjlpXaX0dJno_SuvsVNIZy~VrxqIk91_5h; _bee=WLXKXRSXMjUTEOOp1Faa5iaervzBtamy; _f77=23aba122-f0a9-4b49-acc0-c17c9e62c3fe; _a42=8373db94-9a3d-4768-9308-43ee1f39df97; rckk=WLXKXRSXMjUTEOOp1Faa5iaervzBtamy; ru1k=23aba122-f0a9-4b49-acc0-c17c9e62c3fe; ru2k=8373db94-9a3d-4768-9308-43ee1f39df97; SUB_PASS_ID=eyJ0IjoieHpQOXVURjI5QmNaalRUZVl6YS8wR01zTHg1YnV6RWZKUmFDdWJTbTFVQmhtSkVNZk1TTG01dE5SaXhaY01DdiIsInYiOjEsInMiOjEwMDAwLCJ1IjoyMzc2MjA5MDUyOTAyMX0=";
    public static final String  ANTI_CONTENT = "0aqAfx5eMwCEnKhhPUcNFiovEEpXUuE2tRFdM7ExjGasg5cEA-VF9IU1Y4JXJrb1OHTqVHkFs8vb_lDrVaCnecuEa8T8OqhcCuPrz27QTRUcHBHQWRVqH4X7AOGUfH9Dc0Nd37VB3o-n42j5Nj3fe9LxAki9y5ceTOL9k_8Og7W2vPD8APFCLSg_Di9vnPZPGzfG7d6V0KlKzL9IDpJE4I53pAEMCZMXVu4I2j9_VsPFF85q54YwzA3w7vB_d-2OezRWSsIpU3IUv38kzfze-3LDMfMwMMR7SfRHS3LWS3tO732d73tk7tfDSfwkMfft1qDM1feECF-h2T-11vb1cZkBfMeMeCEMfIK1w7-3iHM1hkvIVz7xfuU3IDkB1IDB2UEBxhez2CeM50EAiVLlqYCrM7YU0XqcpTJO09aXpTJX5zYXG7TVkZy2Bf0PNh92OAPYITCINptYX14xK1_JFqIYfqmw6jpQTXs0uFg3XqNUoYZ0BOsYrq_j2asKP44Wr24VPtVTDqVkDq31Kf5TdslkSVIUSuMZDL1ODMAOeM4VHu6ZtRQ5UfleSkICScImSkR1KfY2c02IWIBxOeL2Z4KgfqE--Zd4u7_K2swU2Oedw4T-vXTUwVVUltv-xNW7s1z6lDSBvvesjeddAZeDzUED3HwTDpt4_kUVDiR4ZZTsyCb38EBAHhSAwzBB2K3l5IswZwSs5IM8iIhinFBl67MuGh84aa9urQ3yB54aXPF";

    public static final String mallid = "634418221618660";


    public static void main(String[] args) throws IOException {
//         TemuMockResponse mockResponse =   userInfo();
//         System.err.println(JsonUtil.objectToString(mockResponse));


//        String uploadSign =  get_signature();
//        Map<String,Object> result = batchUpload(uploadSign, "/Users/mijiuye/Desktop/avatar.png");
//        System.err.println(JsonUtil.objectToString(result));

        product_draft_add();
    }


    /**
     * 素材创建
     */
    public void material_create(){
        String url ="https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gmp/bg/phoenix/api/material/create";
        String json = "{\"folderId\":0,\"createDetailList\":[{\"materialType\":1,\"materialMd5\":\"9c4ead118d047300de3d136558de6201\",\"materialName\":\"avatar\"}]}";


        Map<String,String> headers = new HashMap<>();
        headers.put("accept","*/*");
        headers.put("accept-encoding","gzip, deflate, br, zstd");
        headers.put("accept-language","zh-CN,zh;q=0.9");
        headers.put("anti-content", ANTI_CONTENT);
        headers.put("cache-control","max-age=0");
        headers.put("cookie",COOKIE);
        headers.put("mallid",mallid);
        headers.put("origin","https://seller.kuajingmaihuo.com");
        headers.put("content-type","application/json");
        headers.put("priority","u=1, i");
        headers.put("sec-ch-ua","\"Not(A:Brand\";v=\"99\", \"Google Chrome\";v=\"133\", \"Chromium\";v=\"133\"");
        headers.put("sec-ch-ua-mobile","?0");
        headers.put("sec-ch-ua-platform","\"macOS\"");
        headers.put("sec-fetch-dest","empty");
        headers.put("sec-fetch-mode","cors");
        headers.put("sec-fetch-site","same-origin");
        headers.put("user-agent",USER_AGENT);



        try (Response response = OkHttpClient.post(url, headers, json)){
            System.out.println(response.code());
//            System.out.println(response.headers());
            if( response.isSuccessful()){
                InputStream inputStream = response.body().byteStream();
                InputStream decompressedStream = new GZIPInputStream(inputStream);
                TemuMockResponse mockResponse =   JsonUtil.getObjectMapper().readValue(decompressedStream, TemuMockResponse.class);
                System.err.println(JsonUtil.objectToString(mockResponse));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 素材编辑
     */
    public void material_edit(){
        String url ="https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/gmp/bg/phoenix/api/material/edit";
        String json = "{\"id\":250315445325483,\"url\":\"https://img.cdnfe.com/product/201a0dab759/858daf99-3232-4683-8d18-fc62888529a6_200x200.png\",\"materialName\":\"avatar\",\"uploadStatus\":3,\"materialType\":1}";

        Map<String,String> headers = new HashMap<>();
        headers.put("accept","*/*");
        headers.put("accept-encoding","gzip, deflate, br, zstd");
        headers.put("accept-language","zh-CN,zh;q=0.9");
        headers.put("anti-content", ANTI_CONTENT);
        headers.put("cache-control","max-age=0");
        headers.put("cookie",COOKIE);
        headers.put("mallid",mallid);
        headers.put("origin","https://seller.kuajingmaihuo.com");
        headers.put("content-type","application/json");
        headers.put("priority","u=1, i");
        headers.put("sec-ch-ua","\"Not(A:Brand\";v=\"99\", \"Google Chrome\";v=\"133\", \"Chromium\";v=\"133\"");
        headers.put("sec-ch-ua-mobile","?0");
        headers.put("sec-ch-ua-platform","\"macOS\"");
        headers.put("sec-fetch-dest","empty");
        headers.put("sec-fetch-mode","cors");
        headers.put("sec-fetch-site","same-origin");
        headers.put("user-agent",USER_AGENT);



        try (Response response = OkHttpClient.post(url, headers, json)){
            System.out.println(response.code());
//            System.out.println(response.headers());
            if( response.isSuccessful()){
                InputStream inputStream = response.body().byteStream();
                InputStream decompressedStream = new GZIPInputStream(inputStream);
                TemuMockResponse mockResponse =   JsonUtil.getObjectMapper().readValue(decompressedStream, TemuMockResponse.class);
                System.err.println(JsonUtil.objectToString(mockResponse));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 用户信息
     * @return
     * @throws IOException
     */
    public static TemuMockResponse userInfo() throws IOException {
        Map<String,String> headers = new HashMap<>();
        headers.put("anti-content",ANTI_CONTENT);
        headers.put("cookie",COOKIE);
        headers.put("user-agent",USER_AGENT);

        TemuMockResponse mockResponse= null;
        Map<String,Object> body = new HashMap<>();
        try (Response response = OkHttpClient.post(BASE_URL + "/userInfo", headers,JsonUtil.objectToString(body))){
           if( response.isSuccessful()){
                mockResponse =  JsonUtil.readValue(response.body().bytes(),TemuMockResponse.class);
           }
        }
        return mockResponse;
    }


    /**
     * 批量上传图片
     */
    public static Map<String,Object> batchUpload(String uploadSign, String fileUrl) throws IOException {
        String url ="https://file.kuajingmaihuo.com/api/galerie/v3/store_image?sdk_version=js-0.0.19-alpha.0&tag_name=product-material-tag" ;


        Map<String, String> headers = new HashMap<>();
        headers.put("content-type","multipart/form-data");
        headers.put("cookie", COOKIE);
        headers.put("user-agent", USER_AGENT);

        Path path = Paths.get(fileUrl);
        File file = path.toFile();
        String mimeType = Files.probeContentType(path);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", file.getName(), RequestBody.create(MediaType.parse(mimeType), file))
                .addFormDataPart("url_width_height", "true")
                .addFormDataPart("upload_sign",uploadSign)
                .build();


        try (Response response = OkHttpClient.upload(url, headers, requestBody)){
            if( response.isSuccessful()){
               Map<String,Object> result = JsonUtil.readValue(response.body().bytes(),Map.class);
               return result;
            }
        }
        return null;
    }

    public static String get_signature(){
        String url = "https://seller.kuajingmaihuo.com/galerie/business/get_signature?sdk_version=js-0.0.19-alpha.0&tag_name=product-material-tag";

        Map<String,String> headers = new HashMap<>();
        headers.put("cookie",COOKIE);
        headers.put("user-agent",USER_AGENT);
        headers.put("content-type", "application/json");


        Map<String,Object> body = new HashMap<>();
        body.put("bucket_tag","product-material-tag");

        TemuMockResponse mockResponse= null;

        try (Response response = OkHttpClient.post(url, headers, JsonUtil.objectToString(body))){
            if( response.isSuccessful()){
                mockResponse =  JsonUtil.readValue(response.body().bytes(),TemuMockResponse.class);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if(mockResponse.success){
          Map<String,String> result = (Map<String, String>)  mockResponse.result;
          return result.get("signature");
        }

        return null;
    }




    public static void product_draft_add() throws IOException {
        String url = "https://seller.kuajingmaihuo.com/bg-visage-mms/product/draft/add";
        String json = "{\"catId\":12193}";


        Map<String,String> headers = new HashMap<>();
        headers.put("accept","*/*");
        headers.put("accept-encoding","gzip, deflate, br, zstd");
        headers.put("accept-language","zh-CN,zh;q=0.9");
        headers.put("anti-content", ANTI_CONTENT);
        headers.put("cache-control","max-age=0");
        headers.put("cookie",COOKIE);
        headers.put("mallid",mallid);
        headers.put("origin","https://seller.kuajingmaihuo.com");
        headers.put("content-type","application/json");
        headers.put("priority","u=1, i");
        headers.put("sec-ch-ua","\"Not(A:Brand\";v=\"99\", \"Google Chrome\";v=\"133\", \"Chromium\";v=\"133\"");
        headers.put("sec-ch-ua-mobile","?0");
        headers.put("sec-ch-ua-platform","\"macOS\"");
        headers.put("sec-fetch-dest","empty");
        headers.put("sec-fetch-mode","cors");
        headers.put("sec-fetch-site","same-origin");
        headers.put("user-agent",USER_AGENT);



        try (Response response = OkHttpClient.post(url, headers, json)){
            System.out.println(response.code());
//            System.out.println(response.headers());
            if( response.isSuccessful()){
                InputStream inputStream = response.body().byteStream();
                InputStream decompressedStream = new GZIPInputStream(inputStream);
                TemuMockResponse mockResponse =   JsonUtil.getObjectMapper().readValue(decompressedStream, TemuMockResponse.class);
                System.err.println(JsonUtil.objectToString(mockResponse));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 保存到草稿箱
     * @return
     */
    public static Map<String,String> product_draft_save() throws IOException {
        String url = "https://seller.kuajingmaihuo.com/bg-visage-mms/product/draft/save";

        String json = "{\"cat1Id\":9711,\"cat2Id\":12015,\"cat3Id\":12138,\"cat4Id\":12174,\"cat5Id\":12193,\"cat6Id\":0,\"cat7Id\":0,\"cat8Id\":0,\"cat9Id\":0,\"cat10Id\":0,\"materialMultiLanguages\":[],\"productName\":\"玫瑰花2墙面装饰艺术，7.87英寸圆形木制标志，适用于家居、咖啡馆、酒吧、美容室、卧室、节日装饰和礼品\",\"productPropertyReqs\":[{\"valueUnit\":\"\",\"propValue\":\"复古\",\"propName\":\"风格\",\"refPid\":19,\"vid\":136,\"controlType\":1,\"pid\":3,\"templatePid\":1005869,\"valueExtendInfo\":\"\"},{\"valueUnit\":\"\",\"propValue\":\"人造木材\",\"propName\":\"材料\",\"refPid\":121,\"vid\":2159,\"controlType\":1,\"pid\":89,\"templatePid\":1005866,\"valueExtendInfo\":\"\"},{\"valueUnit\":\"\",\"propValue\":\"壁挂\",\"propName\":\"安装类型\",\"refPid\":127,\"vid\":2997,\"controlType\":1,\"pid\":119,\"templatePid\":1005868,\"valueExtendInfo\":\"\"},{\"valueUnit\":\"\",\"propValue\":\"入口\",\"propName\":\"产品推荐用途\",\"refPid\":205,\"vid\":3797,\"controlType\":1,\"pid\":93,\"templatePid\":1005867,\"valueExtendInfo\":\"\"},{\"valueUnit\":\"\",\"propValue\":\"无需接电使用\",\"propName\":\"供电方式\",\"refPid\":1561,\"vid\":36627,\"controlType\":1,\"pid\":1425,\"templatePid\":1005873,\"valueExtendInfo\":\"\"}],\"productSkcReqs\":[{\"previewImgUrls\":[\"https://img.cdnfe.com/product/fancy/bb0954ba-5634-4ffe-b2fd-c3f98af0168b.jpg\"],\"productSkcCarouselImageI18nReqs\":[],\"extCode\":\"\",\"mainProductSkuSpecReqs\":[{\"parentSpecId\":0,\"parentSpecName\":\"\",\"specId\":0,\"specName\":\"\"}],\"productSkuReqs\":[{\"thumbUrl\":\"\",\"productSkuThumbUrlI18nReqs\":[],\"extCode\":\"\",\"supplierPrice\":1100,\"currencyType\":\"CNY\",\"productSkuSpecReqs\":[{\"parentSpecId\":3001,\"parentSpecName\":\"尺码\",\"specId\":66836542,\"specName\":\"8x8英寸\",\"specLangSimpleList\":[]}],\"productSkuId\":0,\"productSkuSuggestedPriceReq\":{\"suggestedPrice\":200,\"suggestedPriceCurrencyType\":\"USD\"},\"productSkuUsSuggestedPriceReq\":{},\"productSkuWhExtAttrReq\":{\"productSkuVolumeReq\":{\"len\":200,\"width\":200,\"height\":10},\"productSkuWeightReq\":{\"value\":35000},\"productSkuBarCodeReqs\":[],\"productSkuSensitiveAttrReq\":{\"isSensitive\":0,\"sensitiveList\":[]},\"productSkuSensitiveLimitReq\":{}},\"productSkuMultiPackReq\":{\"skuClassification\":1,\"numberOfPieces\":1,\"pieceUnitCode\":1,\"productSkuNetContentReq\":{}},\"productSkuAccessoriesReq\":{\"productSkuAccessories\":[]},\"productSkuNonAuditExtAttrReq\":{}}],\"productSkcId\":0,\"isBasePlate\":0}],\"productSpecPropertyReqs\":[{\"parentSpecId\":3001,\"parentSpecName\":\"尺码\",\"specId\":66836542,\"specName\":\"8x8英寸\",\"vid\":0,\"specLangSimpleList\":[],\"refPid\":0,\"pid\":0,\"templatePid\":0,\"propName\":\"尺码\",\"propValue\":\"8x8英寸\",\"valueUnit\":\"\",\"valueGroupId\":0,\"valueGroupName\":\"\",\"valueExtendInfo\":\"\"}],\"carouselImageUrls\":[\"https://img.cdnfe.com/product/fancy/bb0954ba-5634-4ffe-b2fd-c3f98af0168b.jpg\",\"https://img.cdnfe.com/product/fancy/439a745b-1fd4-48bc-8e9c-f214a6709d6c.jpg\",\"https://img.cdnfe.com/product/fancy/0ab91191-2568-49ba-8f5f-938571b4a86c.jpg\",\"https://img.cdnfe.com/product/fancy/ba9e5b65-6467-48a0-9661-e693498f10f3.jpg\",\"https://img.cdnfe.com/product/fancy/f69814f1-f657-4aa0-9244-32d6bde17ec6.jpg\",\"https://img.cdnfe.com/product/fancy/f69814f1-f657-4aa0-9244-32d6bde17ec6.jpg\"],\"carouselImageI18nReqs\":[],\"materialImgUrl\":\"https://img.cdnfe.com/product/fancy/bb0954ba-5634-4ffe-b2fd-c3f98af0168b.jpg\",\"goodsLayerDecorationReqs\":[],\"goodsLayerDecorationCustomizeI18nReqs\":[],\"sizeTemplateIds\":[],\"showSizeTemplateIds\":[],\"goodsModelReqs\":[],\"productWhExtAttrReq\":{\"outerGoodsUrl\":\"\",\"productOrigin\":{\"countryShortName\":\"CN\",\"region2Id\":43000000000006}},\"productCarouseVideoReqList\":[],\"goodsAdvantageLabelTypes\":[],\"productDetailVideoReqList\":[],\"productOuterPackageImageReqs\":[{\"imageUrl\":\"https://kjpfs-cn.kuajingmaihuo.com/product-material-private-tag/201a0dab759/c267476f-05fb-4c85-a59c-679e6eadf672_800x800.jpeg\"}],\"productOuterPackageReq\":{\"packageShape\":0,\"packageType\":1},\"sensitiveTransNormalFileReqs\":[],\"productGuideFileI18nReqs\":[],\"productSaleExtAttrReq\":{},\"productNonAuditExtAttrReq\":{\"california65WarningInfoReq\":{},\"cosmeticInfoReq\":{}},\"personalizationSwitch\":0,\"productComplianceStatementReq\":{\"protocolVersion\":\"V1.0\",\"protocolUrl\":\"https://bdl.cdnfe.com/upload_bdl/seller-protocol/00f56a69-7bee-4768-8cef-e1682ffd58e3.html\"},\"productOriginCertFileReqs\":[],\"productDraftId\":702704775}";

        MockProduct product =  JsonUtil.readValue(json.getBytes(), MockProduct.class);
        product.setProductDraftId(104670817);
        json = JsonUtil.objectToString(product);




        Map<String,String> headers = new HashMap<>();
        headers.put("accept","*/*");
        headers.put("accept-encoding","gzip, deflate, br, zstd");
        headers.put("accept-language","zh-CN,zh;q=0.9");
        headers.put("anti-content", ANTI_CONTENT);
        headers.put("cache-control","max-age=0");
        headers.put("cookie",COOKIE);
        headers.put("mallid",mallid);
        headers.put("origin","https://seller.kuajingmaihuo.com");
        headers.put("content-type","application/json");
        headers.put("priority","u=1, i");
        headers.put("sec-ch-ua","\"Not(A:Brand\";v=\"99\", \"Google Chrome\";v=\"133\", \"Chromium\";v=\"133\"");
        headers.put("sec-ch-ua-mobile","?0");
        headers.put("sec-ch-ua-platform","\"macOS\"");
        headers.put("sec-fetch-dest","empty");
        headers.put("sec-fetch-mode","cors");
        headers.put("sec-fetch-site","same-origin");
        headers.put("user-agent",USER_AGENT);



        try (Response response = OkHttpClient.post(url, headers, json)){
            System.out.println(response.code());
//            System.out.println(response.headers());
            if( response.isSuccessful()){

                InputStream inputStream = response.body().byteStream();
                InputStream decompressedStream = new GZIPInputStream(inputStream);
                TemuMockResponse mockResponse =   JsonUtil.getObjectMapper().readValue(decompressedStream, TemuMockResponse.class);
                System.err.println(JsonUtil.objectToString(mockResponse));

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return null;
    }







    /**
     * Temu Mock Response
     */
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class TemuMockResponse {
        public TemuMockResponse(){}
        private boolean success;
        private int errorCode;
        private String errorMsg;
        private Object result;
        public boolean isSuccess() { return success; }
        public int getErrorCode() { return errorCode; }
        public String getErrorMsg() { return errorMsg; }
        public Object getResult() { return result; }
    }





}
